<template>
<div>
  <ButtonGroup>
      <!-- 添加分类选择按钮 -->
        <Button type="primary" @click='changetype(0)'>新闻分类</Button>
        <Button type="primary" @click='changetype(1)'>用户分类</Button>
        <Button type="primary" @click='changetype(2)'>产品分类</Button>
    </ButtonGroup>
    
    <!-- 渲染树状结构 -->
    <Row>
        <Col span="6">
          <Tree :data="data" :render="renderContent"></Tree>
        </Col>        
    </Row>
    
     
     <!-- 创建分类时form表单提交 -->
     <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
        
        <!-- 选择分类 -->
        <FormItem label="分类标题" prop="title">
            <Input v-model="formValidate.title" placeholder="请输入分类标题"></Input>
        </FormItem>
        
        <!-- 选择属于哪一类 -->
        <FormItem label="分类类型 Id" prop="type">
            <Input v-model="formValidate.type" placeholder="请输入父类"></Input>
        </FormItem>
       
        <!-- 选择从属哪一类（父节点） -->
        <FormItem label="父类 Id" prop="parentId">
            <Input v-model="formValidate.parentId" placeholder="请输入父类"></Input>
        </FormItem>

        <!-- 提交和重置按钮 -->
        <FormItem>
            <!-- 提交按钮 -->
            <Button type="primary" @click="handleSubmit('formValidate')">Submit</Button>
           <!-- 重置按钮 -->
            <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px">Reset</Button>
        </FormItem>

    </Form>


    </div>
</template>
<script>
export default {
  data() {
    return {
      data: [],
      formValidate: {//表单的数据
        title: "",//添加类型的名称
        parentId:null,//父类的id值
        type:'',  //属于哪一类 
       
      },
      ruleValidate: {//表单的限定条件
        title: [
          {
            required: true,
            message: "The name cannot be empty",
            trigger: "blur"
          }
        ]
      },

      buttonProps: {//提交按钮的数据
        type: "ghost",
        size: "small"
      }
    };
  },
  created() {//g钩子函数，创建完成后就渲染数据
    this.getData();
  },

  methods: {
    changetype(type){//选择添加类型（传入的数据为0，1，2.。。）
         
      this.formValidate.type=type;
      this.getData(this.formValidate.type);  //重新渲染页面
    },
    getData(type) {//ajax请求后端，                   更新数据
      var type=type || 0;//默认type传入后端为0
      this.$http.post(`http://10.31.153.35:3000/cate/list/${type}`).then(response => {
        this.data = response.data;//树状结构模块获取data即时更新
        this.data[0].expand= true;
        // console.log(response.data);
      });
    },

    handleSubmit(name) {//往数据库创建数据
      this.$refs[name].validate(valid => {
        if (valid) {//验证表单是否填写正确格式
          //ajax数据请求    

          this.$http({
            method: "post",
            url: "http://10.31.153.35:3000/cate/data",
            data: this.formValidate,//讲表单中的数据提交到后端
          }).then(res => {
           
            this.$Message.success("Success!");
            this.changetype(this.formValidate.type);//这里保证了结构更新和页面停留
           
           // console.log(this.$data.formValidate,1111)
            // console.log(this.$options.data(),2222)
            //重置form表单内容为初始值，初始值就是刚开始的title值
            
            //*******************非常重要 */          
            Object.assign(this.$data.formValidate
            ,this.$options.data().formValidate)//重置表单为初始状态      
          });                   
        } else {
          this.$Message.error("填写错误!");
        }
      });
    },
    handleReset(name) {//重置表单
      this.$refs[name].resetFields();
    },
    renderContent(h, { root, node, data }) {
      return h(
        "span",
        {
          style: {
            display: "inline-block",
            width: "100%"
          }
        },
        [
          h("span", [
            h("Icon", {
              props: {
                type: "ios-paper-outline"
              },
              style: {
                marginRight: "8px"
              }
            }),
            h("span", data.title)
          ]),
          h(
            "span",
            {
              style: {
                display: "inline-block",
                float: "right",
                marginRight: "32px"
              }
            },
            [
              h("Button", {
                props: Object.assign({}, this.buttonProps, {
                  icon: "plus"
                }),
                style: {
                  marginRight: "8px",
                  color: "blue",
                  width: "100%",
                  background:"#ddd"
                },
                on: {
                  click: () => {
                    this.formValidate.parentId=data._id;
                   
                  }
                }
              }),
              h("Button", {
                props: Object.assign({}, this.buttonProps, {
                  icon: "trash-a"
                }),
                style: {
                  // marginRight: "8px",
                  color: "red",
                  width: "100%",
                  background:"#ddd"
                },
                on: {
                  click: () => {

                    this.remove(root, node, data);
                      
                  }
                }
              })
            ]
          )
        ]
      );
    },
   
    remove(root, node, data) {//删除数据
      this.$Modal.confirm({
        title: 'Title',
        content: '<p>确认删除？</p>',
        onOk: () => {
            // this.$Message.info('Clicked ok');
            // console.log(params.row._id);
            this.$http({
                method:'delete',
                url:`http://10.31.153.35:3000/cate/data/${data._id}`
            }).then(res=>{
                this.$Message.info('Clicked ok');
                this.getData();
                this.changetype(this.formValidate.type);//这里保证了结构更新和页面停留

            })
        },
        onCancel: () => {
            this.$Message.info('Clicked cancel');
        }
    });

     
    }
  }
};
</script>
